package com.zsummer.design.create.prototype;

import java.io.*;

/**
 * @author zsummer
 * 2020/3/22 12:03
 * 原型模式
 */
public class Client {
    public static void main(String[] args) {
        Pet dog = new Pet("dog");
        Person person = new Person("zhangSan", dog);
        try {
            // 浅拷贝，实现Cloneable接口，重写Clone方法
            Person clonePerson = person.clone();
            System.out.println(person.getPet() == clonePerson.getPet()); // true
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos)){
            oos.writeObject(person);

            try (ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
                 ObjectInputStream ois = new ObjectInputStream(bis)){
                // 深拷贝，只需要实现Serializable接口即可
                Person deepCopyPerson = (Person)ois.readObject();
                System.out.println(person.getPet() == deepCopyPerson.getPet()); // false
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class Person implements Cloneable, Serializable{
    private String name;
    private Pet pet;

    @Override
    public Person clone() throws CloneNotSupportedException {
        return (Person) super.clone();
    }

    public Person(String name, Pet pet) {
        this.name = name;
        this.pet = pet;
    }

    public Pet getPet() {
        return pet;
    }
}

class Pet implements Serializable{
    private String type;

    public Pet(String type) {
        this.type = type;
    }
}
